<template>
  <el-row :gutter="20">
    <el-col :span="16"
      ><div class="grid-content bg-purple" />
      <el-card class="calendar-card">
        <el-calendar ref="calendar">
          <template #header="{ date }">
            <span>{{ date }}</span>
            <el-button-group>
              <el-button size="small" @click="selectDate('prev-year')"
                >Previous Year</el-button
              >
              <el-button size="small" @click="selectDate('prev-month')"
                >Previous Month</el-button
              >
              <el-button size="small" @click="selectDate('today')"
                >Today</el-button
              >
              <el-button size="small" @click="selectDate('next-month')"
                >Next Month</el-button
              >
              <el-button size="small" @click="selectDate('next-year')"
                >Next Year</el-button
              >
            </el-button-group>
          </template>

          <template #dateCell="{ data }">
            <div @click="handleDialog(data.day)">
              {{ data.day.split("-").slice(1).join("-") }}
              <br />
              <span v-if="calendar_consultant.indexOf(data.day) > -1"
                >咨询师数：{{
                  consultantCount[calendar_consultant.indexOf(data.day)]
                }}<br
              /></span>
              <span v-if="calendar_supervisor.indexOf(data.day) > -1"
                >督导数：{{
                  supervisorCount[calendar_supervisor.indexOf(data.day)]
                }}</span
              >
            </div>
          </template>
        </el-calendar>
      </el-card>
    </el-col>
    <el-col :span="1"></el-col>
    <el-col :span="3">
      <el-card class="left-bar">
        <template #header>咨询师</template>
        <el-button
          type="text"
          class="text-button"
          @click="dialogVisible_consultant = true"
          >添加排班</el-button
        >
        <el-scrollbar maxHeight="600px">
          <p v-for="item in dayList_counsellors.values" :key="item.name">
            {{ item.name }}
            <el-button
              type="danger"
              @click="handleDelete_consultant(item.arrangeID)"
              :icon="Delete"
            ></el-button>
          </p>
        </el-scrollbar>
      </el-card>
    </el-col>
    <!-- <el-col :span="2"></el-col> -->
    <el-col :span="3">
      <el-card class="left-bar">
        <template #header>督导</template>
        <el-button
          type="text"
          class="text-button"
          @click="dialogVisible_supervisor = true"
          >添加排班</el-button
        >
        <el-scrollbar maxHeight="600px">
          <p v-for="item in dayList_supervisor.values" :key="item.name">
            {{ item.name }}
            <el-button
              type="danger"
              @click="handleDelete_supervisor(item.arrangeID)"
              :icon="Delete"
            ></el-button>
          </p>
        </el-scrollbar>
      </el-card>
    </el-col>
  </el-row>

  <el-dialog
    v-model="dialogVisible_consultant"
    title="添加咨询师"
    width="200px"
  >
    <!-- <el-form :model="form">
      <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose_consultant">取消</el-button>
        <el-button type="primary" @click="handleConfirm_consultant"
          >确认</el-button
        >
      </span>
    </template> -->

    <el-scrollbar maxHeight="400px">
      <p v-for="item in consultantList" :key="item.name" class="scrollbar-item">
        {{ item.name }}
        <el-button
          type="primary"
          @click="handleConfirm_consultant(item.name)"
          class="scrollbar-button"
          >添加</el-button
        >
      </p>
    </el-scrollbar>
  </el-dialog>

  <el-dialog v-model="dialogVisible_supervisor" title="添加督导" width="200px">
    <!-- <el-form :model="form">
      <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose_supervisor">取消</el-button>
        <el-button type="primary" @click="handleConfirm_supervisor"
          >确认</el-button
        >
      </span>
    </template> -->

    <el-scrollbar maxHeight="400px">
      <p v-for="item in supervisorList" :key="item.name" class="scrollbar-item">
        {{ item.name }}
        <el-button
          type="primary"
          @click="handleConfirm_supervisor(item.name)"
          class="scrollbar-button"
          >添加</el-button
        >
      </p>
    </el-scrollbar>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, ref } from "vue";
import {
  getOnlineTable_consultant,
  getOnlineTable_supervisor,
  addSchedule,
  searchSchedule,
  deleteSchedule,
  searchSchedule_month,
} from "@/service/api_admin";
import { Delete } from "@element-plus/icons-vue";
const dialogVisible_consultant = ref(false);
const dialogVisible_supervisor = ref(false);
let clickDate = "";

const form = reactive({
  name: "",
  time: 0,
});

const dayList_counsellors = reactive([
  {
    name: "",
  },
]);

const dayList_supervisor = reactive([
  {
    name: "",
  },
]);

const consultantList = ref([
  {
    counsellorID: "",
    name: "",
  },
]);
const supervisorList = ref([
  {
    counsellorID: "",
    name: "",
  },
]);
const initUserList = async () => {
  //获取咨询师详情名单
  const res1 = await getOnlineTable_consultant();
  consultantList.value = res1.data.result.counsellorList;
  //获取督导详情名单
  const res2 = await getOnlineTable_supervisor();
  supervisorList.value = res2.data.result.counsellorList;
};

initUserList();

let calendar_consultant = ref([""]);
let calendar_supervisor = ref([""]);
let consultantCount = ref([0]);
let supervisorCount = ref([0]);
let nowDate = new Date();
let year = nowDate.getFullYear();
let month = nowDate.getMonth(); //获取的月份从0开始
const leap_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const common_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const calendar = ref();

const refreshSchedule = async () => {
  let time = 0;
  //获取时间戳，单位秒
  if (clickDate != "") {
    time = new Date(clickDate).getTime();
    time = time / 1000;
  } else {
    //是否填充0
    let monthStr = "";
    let dayStr = "";
    let realMonth = month + 1;
    if (month < 10) {
      monthStr = "0" + realMonth;
    } else {
      monthStr = "" + realMonth;
    }

    let day = new Date().getDate();
    console.log("day", day);
    if (day < 10) {
      dayStr = "0" + day;
    } else {
      dayStr = "" + day;
    }
    clickDate = year + "-" + monthStr + "-" + dayStr;
    console.log("clickDate", clickDate);
    time = new Date(clickDate).getTime();
    time = time / 1000; //13位时间戳转换为10位
    console.log("time", time);
  }
  //获取当天的排班列表
  const res = await searchSchedule(time);
  //设置渲染内容
  dayList_counsellors.values = res.data.result.counsellors;
  dayList_supervisor.values = res.data.result.supervisors;
};

const getPageInfo = async () => {
  calendar_consultant.value = [];
  calendar_supervisor.value = [];
  consultantCount.value = [];
  supervisorCount.value = [];

  //判断平闰年
  let maxDay = 0;
  if (year % 100 == 0) {
    if (year % 400 == 0) {
      maxDay = leap_month[month];
    } else {
      maxDay = common_month[month];
    }
  } else {
    if (year % 4 == 0) {
      maxDay = leap_month[month];
    } else {
      maxDay = common_month[month];
    }
  }

  //是否填充0
  let monthStr = "";
  let dayStr = "";
  let realMonth = month + 1;
  if (month < 10) {
    monthStr = "0" + realMonth;
  } else {
    monthStr = "" + realMonth;
  }

  let arrangeTimeList: number[] = [];
  let params: string[] = [];
  for (let num = 1; num <= maxDay; num++) {
    if (num < 10) {
      dayStr = "0" + num;
    } else {
      dayStr = "" + num;
    }
    const param = year + "-" + monthStr + "-" + dayStr;
    let option = new Date(param).getTime();
    option = option / 1000; //13位时间戳转换为10位
    params.push(param);
    arrangeTimeList.push(option);
  }
  const get_res = await searchSchedule_month(arrangeTimeList);
  const res = get_res.data.result;
  // console.log("-----");
  // console.log(res);

  for (let num = 0; num < maxDay; num++) {
    const consultantData = res[num].counsellors;
    const supervisorData = res[num].supervisors;

    // console.log("=====");
    // console.log(consultantData);
    // console.log(supervisorData);
    for (let i = 0; i < consultantData.length; ++i) {
      let index = calendar_consultant.value.indexOf(params[num]);
      if (index == -1) {
        calendar_consultant.value.push(params[num]);
        consultantCount.value.push(1);
      } else {
        consultantCount.value[index]++;
      }
    }

    for (let i = 0; i < supervisorData.length; ++i) {
      let index = calendar_supervisor.value.indexOf(params[num]);
      if (index == -1) {
        calendar_supervisor.value.push(params[num]);
        supervisorCount.value.push(1);
      } else {
        supervisorCount.value[index]++;
      }
    }
  }
};

const selectDate = (val: string) => {
  calendar.value.selectDate(val);
  if (val == "prev-year") {
    year--;
  } else if (val == "next-year") {
    year++;
  } else if (val == "prev-month") {
    if (month == 0) {
      year--;
      month = 11;
    } else {
      month--;
    }
  } else if (val == "next-month") {
    if (month == 1) {
      year++;
      month = 0;
    } else {
      month++;
    }
  }
  // clickDate = "";
  if (val == "today") {
    let realYear = new Date().getFullYear();
    let monthStr = "";
    let dayStr = "";
    let realMonth = 1 + new Date().getMonth();
    let realDay = new Date().getDate();
    if (realMonth < 10) {
      monthStr = "0" + realMonth;
    } else {
      monthStr = "" + realMonth;
    }
    if (realDay < 10) {
      dayStr = "0" + realDay;
    } else {
      dayStr = "" + realDay;
    }
    //不在今天所在的年月时，要将日历的年月属性重新设定
    if (month != realMonth - 1 || year != realYear) {
      year = new Date().getFullYear();
      month = new Date().getMonth();
      getPageInfo();
    }
    clickDate = realYear + "-" + monthStr + "-" + dayStr;
    console.log("clickDate", clickDate);
    let time = new Date(clickDate).getTime();
    time = time / 1000; //13位时间戳转换为10位
    console.log("time", time);
  } else {
    getPageInfo();
  }

  refreshSchedule();
};

const handleDialog = async (date: string) => {
  //获取时间戳，单位秒
  console.log("handleDialog date:", date);
  let time = new Date(date).getTime();
  time = time / 1000;
  clickDate = date;
  console.log("clickDate", clickDate);
  console.log("time", time);

  year = new Date(date).getFullYear();
  month = new Date(date).getMonth();

  refreshSchedule();
  form.time = time;
};

const handleConfirm_consultant = async (name: string) => {
  //查找咨询师并获取id，然后添加排班
  const list = consultantList.value;
  for (let i = 0; i < list.length; ++i) {
    if (name == list[i].name) {
      if (form.time == 0) {
        let time = new Date(clickDate).getTime();
        form.time = time / 1000;
      }
      const msg_res = await addSchedule(form.time, list[i].counsellorID);
      // console.log(msg_res);
      if (msg_res.data.code == 0) {
        ElMessage({ type: "success", message: "添加成功" });
        dialogVisible_consultant.value = false;
        refreshSchedule();
        getPageInfo();
      } else {
        ElMessage({ type: "warning", message: "添加失败" });
      }
      return;
    }
  }
  ElMessage("无效姓名");
};
const handleConfirm_supervisor = async (name: string) => {
  //查找督导并获取id，然后添加排班
  const list = supervisorList.value;
  for (let i = 0; i < list.length; ++i) {
    // console.log("督导：" + list[i].name);
    if (name == list[i].name) {
      const msg_res = await addSchedule(form.time, list[i].counsellorID);
      // console.log(msg_res);
      if (msg_res.data.code == 0) {
        ElMessage({ type: "success", message: "添加成功" });
        dialogVisible_supervisor.value = false;
        refreshSchedule();
        getPageInfo();
      } else {
        ElMessage({ type: "warning", message: "添加失败" });
      }
      return;
    }
  }
  ElMessage("无效姓名");
};

const handleDelete_consultant = async (arrangeID: number) => {
  ElMessageBox.confirm("将要删除排班，确认继续？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteSchedule(arrangeID);
    refreshSchedule();
    getPageInfo();
  });
};
const handleDelete_supervisor = async (arrangeID: number) => {
  ElMessageBox.confirm("将要删除排班，确认继续？", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const msg_res = await deleteSchedule(arrangeID);

    if (msg_res.data.code == 0) {
      ElMessage({ type: "success", message: "删除成功" });
      dialogVisible_supervisor.value = false;
      refreshSchedule();
      getPageInfo();
    } else {
      ElMessage({ type: "warning", message: "删除失败" });
    }
  });
};

refreshSchedule();
getPageInfo();
</script>

<style lang="less">
.is-selected {
  color: #1989fa;
}
.calendar-card {
  height: 40vw;
}
.el-calendar-table .el-calendar-day {
  height: 5vw;
}
.left-bar {
  height: 40vw;
}
.text-button {
  font-size: 15px;
}
.scrollbar-item {
  display: flex;
  align-items: center;
  justify-content: right;
  border-right: 8vw;
  height: 4vw;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
}
.scrollbar-button {
  display: flex;
  align-items: center;
  justify-content: right;

  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
}
</style>